<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="success" @click="addEdit">新增</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
               <el-select v-model="query.level" placeholder="角色级别" class="handle-select mr10">
                    <!--<el-option key="1" label="1-管理员" value="1"></el-option>
                    <el-option key="2" label="2-辅导员" value="2"></el-option>
                    <el-option key="3" label="3-主席团" value="3"></el-option>
                    <el-option key="4" label="4-部长团" value="4"></el-option>
                    <el-option key="5" label="5-干事" value="5"></el-option>
                    <el-option key="6" label="6-班级负责人" value="6"></el-option>-->
                    <el-option
				      v-for="item in roleOptions"
				      :key="item.roleId"
				      :label="item.description"
				      :value="item.roleId">
				    </el-option>
                </el-select>
                <el-input v-model="query.username" placeholder="用户名" class="handle-input mr10"></el-input>
                <el-input v-model="query.realname" placeholder="真实姓名" class="handle-input mr10"></el-input>
				<el-input v-model="query.departmentName" placeholder="部门" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="" icon="el-icon-brush" @click="clearSearch">清空</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="userId" label="ID" width="160" align="center"></el-table-column>
                <el-table-column prop="userName" width="120"  label="用户名" align="center"></el-table-column>
                <el-table-column prop="realName" width="120" label="真实姓名" align="center"></el-table-column>
                <el-table-column prop="departmentName" width="180" label="部门" align="center"></el-table-column>
                <el-table-column prop="className" label="班级" width="180" align="center"></el-table-column>
                <el-table-column prop="email" label="email" align="center"></el-table-column>
                <el-table-column prop="level" width="120" label="角色级别" align="center" >
                	<template slot-scope="scope" >
				       <!--  基于枚举类的方法 -->
				       <div @click="cellClick(scope.$index, scope.row)">
				       <el-select v-model="value" v-if="showInputStatus==scope.row.userId"
							@change="loseFcous(scope.$index, scope.row)" 
							> 
		                    <el-option
						      v-for="item in roleOptions"
						      :key="item.roleId"
						      :label="item.description"
						      :value="item.roleId">
						    </el-option>
				       </el-select>
							<span style="margin-left: 10px" v-else>{{ enums.levelEnum.getLabelByValue(scope.row.level) }}</span>
						</div>
				   </template>
                </el-table-column>
               <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <!--<el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :title="titleType" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :rules="rules":model="form" label-width="80px">
               <!-- <el-form-item label="用户名">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-input v-model="form.sex"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>-->
                
                <el-form-item label="用户名*">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名*">
                    <el-input v-model="form.realName"></el-input>
                </el-form-item>
                <!--<el-form-item label="设置密码" v-if="operFlag='1'">
                    <el-input v-model="form.usePwd"></el-input>
                </el-form-item>-->
                <el-form-item label="性别">
                    <el-radio-group v-model="form.sex">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="学号*" >
                    <el-input v-model="form.userId" :disabled="this.operFlag=='1'"></el-input>
                </el-form-item>
                <el-form-item label="出生日期">
                    <el-col :span="11">
                        <el-date-picker
                            type="date"
                            placeholder="出生日期"
                            value-format="yyyyMMdd"
                            v-model="form.birth"
                        ></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="地址">
                    <!--<el-cascader @change="selectPlace" :options="options"></el-cascader>-->
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="邮箱地址">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="电话号码">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="身份证">
                    <el-input v-model="form.idCard"></el-input>
                </el-form-item>
                <el-form-item label="所属班级">
                    <el-select @change="classChange" v-model="form.classId" clearable placeholder="请选择">
                      <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门">
                    <el-select @change="departmentChange" v-model="form.departmentId" clearable placeholder="请选择">
                        <el-option v-for="item in departmentList" :key="item.departmentId" :label="item.departmentName" :value="item.departmentId"></el-option>
                    </el-select>
                </el-form-item>
                
                <el-form-item label="角色级别">
                	<el-select v-model="form.level" clearable placeholder="角色级别" class="handle-select mr10">
	                    <el-option
					      v-for="item in roleOptions"
					      :key="item.roleId"
					      :label="item.description"
					      :value="item.roleId">
					    </el-option>
                </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancle">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

	import axios from 'axios'
	import enums from '../common/enums.js'
	export default {
    name: 'basetable',
    data() {
        return {
            query: {
                level: '',
                username:'',
                departmentName:'',
                realname: '',
                pageIndex: 1,
                pageSize: 10
            },
            operFlag:'9',//操作标识：9-初始化 0-新增 1-编辑
            showInputStatus:'',
            titleType:'' ,//此处初始化变量
            value:'',
            instance:null, // axios 实例
            tableData: [],
            enums: enums,
            multipleSelection: [],
            delList: [],
            roleOptions:[],//角色列表选择器
            editVisible: false,
            pageTotal: 0,
            form: {
            	userName : '',
        		address : '',
        		email : '',
        		phone : '',
        		sex	: '',
        		realName:'',
        		birth:'',
        		address:'',
        		idCard:'',
        		classId:'',
        		className:'',
        		departmentId:'',
        		departmentName:'',
        		level:''
            },
            idx: -1,
            id: -1,
            classList:[{
              classId:'1',
              className:'一班'
            },{
              classId:'2',
              className:'二班'
            },{
              classId:'3',
              className:'三班'
            },{
              classId:'4',
              className:'四班'
            }],//班级信息
            departmentList:[{
              departmentId:'1',
              departmentName:'组织部'
            },{
              departmentId:'2',
              departmentName:'志愿服务站'
            },{
              departmentId:'3',
              departmentName:'师友电脑维修部'
            },{
              departmentId:'4',
              departmentName:'办公室'     
            },{
              departmentId:'5',
              departmentName:'学习部'     
            },{
              departmentId:'6',
              departmentName:'文体部'     
            },{
              departmentId:'7',
              departmentName:'宣传部'     
            },{
              departmentId:'8',
              departmentName:'网络技术部'     
            },{
              departmentId:'9',
              departmentName:'外联部'     
            },{
              departmentId:'10',
              departmentName:'辩论队'     
            }],
            form: {
                realName: '阿狸爱乘凉', //真实姓名
                userName: 'alin', //用户名
                sex: '男', //性别
                userId: '201441404222', //学号
                usePwd: '123456', //密码
                birth: '20140408', //出生日期
                address: '广东省东莞市松山湖', //地址
                email: '2983277940@qq.com', //邮箱地址
                idCard: '440981199908218119', //身份证
                phone: '13631789756', //电话号码
                classId: '2', //所属班级
                className: '二班', //所属班级名称
                departmentId: '2', //所属部门
                departmentName: '自律会' //所属部门名称
            },
            options: [
                {
                    value: '广东省',
                    label: '广东省',
                    children: [
                        {
                            value: '广州市',
                            label: '广州市',
                            children: [
                                {
                                    value: '天河区',
                                    label: '天河区'
                                },
                                {
                                    value: '海珠区',
                                    label: '海珠区'
                                }
                            ]
                        },
                        {
                            value: '东莞市',
                            label: '东莞市',
                            children: [
                                {
                                    value: '长安镇',
                                    label: '长安镇'
                                },
                                {
                                    value: '虎门镇',
                                    label: '虎门镇'
                                }
                            ]
                        }
                    ]
                },
                {
                    value: '湖南省',
                    label: '湖南省',
                    children: [
                        {
                            value: '长沙市',
                            label: '长沙市',
                            children: [
                                {
                                    value: '岳麓区',
                                    label: '岳麓区'
                                }
                            ]
                        }
                    ]
                }
            ],
            rules: {
                realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
                userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                usePwd: [{ required: true, message: '请选择密码', trigger: 'blur' }],
                sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
                usePwd: [{ required: true, message: '请选择密码', trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                userId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
                birth: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
                address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
                email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' }],
                idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
                classId: [{ required: true, message: '请选择所属班级', trigger: 'change' }],
                className: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
                departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
                departmentName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
            }
        };
    },
    created() {
    this.instance = axios.create({
//      baseURL:'http://localhost:9000/api',
        timeout:5000
    })
    this.getData()
    
    this.getRoleList();
  },
    methods: {
        //   获取联系人列表
	    async getData(){
	    	
	    	let _this = this;

	        let res = await _this.$Http.getUserList(
	        	{
	        		pageNum:_this.query.pageIndex,
	        	},
                true
	        );
	        
	        console.log(res.data.list);
			let info = res.data.list;
	        this.tableData = info;
	        
	        this.pageTotal = res.data.total || 10;
	    },
	    //获取角色列表
	    async getRoleList(){
	        let res = await this.$Http.getRoleList(
	        	{
	        		pageNum:0,
	        		pageSize:100,
	        	},
                true
	        );
	        this.roleOptions = res.data.list;
	    },
        // 保存编辑
        async saveEdit() {
        	let user = this.form;
        	//检查必输字段
        	if(user.userName=='' || user.userName==undefined){
        		this.$message.error("输入用户名不能为空!");
        		return;
        	}
        	if(user.realName=='' || user.realName==undefined){
        		this.$message.error("输入真实姓名不能为空!");
        		return;
        	}
        	if(user.userId=='' || user.userId==undefined){
        		this.$message.error("输入学号不能为空!");
        		return;
        	}
        	
        	//处理非必输字段
        	user.address = this.isBlank(user.address);
        	user.email = this.isBlank(user.email);
        	user.phone = this.isBlank(user.phone);
        	user.sex = this.isBlank(user.sex);
        	user.birth = this.isBlank(user.birth);
        	user.address = this.isBlank(user.address);
        	user.idCard = this.isBlank(user.idCard);
        	user.classId = this.isBlank(user.classId);
        	user.classId = this.isBlank(user.classId);
        	user.className = this.isBlank(user.className);
        	user.departmentId = this.isBlank(user.departmentId);
        	user.departmentName = this.isBlank(user.departmentName);
        	user.level = this.isBlank(user.level);
            this.editVisible = false;
            
            //新增用户
            if (this.operFlag=='0'){
		        let res = await this.$Http.addUserInfo(
		        	{
		        		userName : user.userName,
		        		address : user.address,
		        		email : user.email,
		        		phone : user.phone,
		        		sex	: user.sex,
		        		realName:user.realName,
		        		userId:user.userId,
		        		birth:user.birth,
		        		address:user.address,
		        		idCard:user.idCard,
		        		classId:user.classId,
		        		className:user.className,
		        		departmentId:user.departmentId,
		        		departmentName:user.departmentName,
		        		level:user.level
		        	},
	                true
		        );
		        console.log(res);
		        if(res.status==0){
		        	this.$message.success(res.msg);
		        	this.getData();
		        }else{
		        	this.$message.error(res.msg);
		        }
	            this.getData();
            }
            
            //修改用户
            if(this.operFlag=='1'){
            	let res = await this.$Http.updateUserInfo(
		        	{
		        		userName : user.userName,
		        		address : user.address,
		        		email : user.email,
		        		phone : user.phone,
		        		sex	: user.sex,
		        		realName:user.realName,
		        		userId:user.userId,
		        		birth:user.birth,
		        		address:user.address,
		        		idCard:user.idCard,
		        		classId:user.classId,
		        		className:user.className,
		        		departmentId:user.departmentId,
		        		departmentName:user.departmentName,
		        		level:user.level
		        	},
	                true
		        );
		        console.log(res);
		        if(res.status==0){
		        	this.$message.success(res.msg);
		        	this.getData();
		        }else{
		        	this.$message.error(res.msg);
		        }
	            this.getData();
            }
            //this.$set(this.tableData, this.idx, this.form);
			//this.$message.error(`操作无效`);
        },
        
		//取消按钮
		cancle(){
			
			this.editVisible = false;
			this.getData();
			
		},
        // 触发搜索按钮
        async handleSearch() {
            let res = await this.$Http.getUserListByParams(
	        	{
	        		pageNum:this.query.pageIndex,
	        		level : this.query.level,
	        		userName : this.query.username,
	        		departmentName:this.query.departmentName,
	        		realName : this.query.realname
	        	},
                true
	        );
	        console.log(res.data);
	        //console.log(res.data.total);
	        this.tableData = res.data.list;
	        this.pageTotal = res.data.total || 10;
        },
        //清空搜索栏
        clearSearch(){
        	this.query.level = ''
        	this.query.realname = ''
        	this.query.username = ''
        	this.query.departmentName = ''
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                    
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            console.log('选择条数：'+length);
            if (length == 0) {this.$message.error(`请选择一条数据`);return;};
            let str = [];
            this.delList = this.delList.concat(this.multipleSelection);
            //console.log('选择信息：'+this.delList);
            for (let i = 0; i < length; i++) {
                str [i]= this.multipleSelection[i].userId;
            }
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
	            	this.delOperate(str);
	            })
            .catch(() => {});
        },
        //执行删除
        async delOperate(value){
            let res = await this.$Http.delUserInfos(
	        	{
	        		ids : value
	        	},
	            true
	        );
            console.log(res);
	        if (res.status == 0){
	        	//this.$message.success(res.msg);
	        	this.delList = [];
	        }
            this.$message.success(res.msg);
            this.getData();
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.operFlag='1';
            this.form.level = Number(row.level); 
            this.titleType ="编辑";
            this.editVisible = true;
        },
        // 新增操作
        addEdit(){
        	this.form={};
        	this.operFlag='0';
        	this.titleType ="新增";
            this.editVisible = true;
        },
		async loseFcous(index, row) {
			//debugger
			console.log("row.userId={},this.value",row.userId,this.value)
			if(this.value==''){
				//this.getData();
				return;
			}
			if(this.value==row.level){
				this.$message.error('角色级别无变更');
				this.value = '';
				//this.getData();
				return;
			}
			//this.$message.error(`失去焦点`+ row.userId);
			let res = await this.$Http.updateUserRole(
	        	{
	        		userId : row.userId,
	        		roleId : this.value,
	        	},
                true
	        );
	        
	        if(res.status==0){
	        	this.$message.success(res.msg);
	        	this.getData();
	        }else{
	        	this.$message.success(res.msg);
	        }
			this.showInputStatus='';
			this.value = '';
		},
		cellClick(index, row) {
			//debugger
			//this.$message.error(`获取焦点`+ row.userId);
			this.value = Number(row.level);
			this.showInputStatus=row.userId;
		},
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        submitForm(form) {
          const {model} = this.$refs[form]
          console.log(model);
          const birth = model.birth.replace(/-/g, "")
          console.log(`${this.$baseUrl}/user/register.do`);
          this.$axios.post(`${this.$baseUrl}/user/register.do`,{
            realName:model.realName,
            userName:model.userName,
            usePwd:model.usePwd,
            sex:model.sex,
            usePwd:model.usePwd,
            password:model.password,
            userId:model.userId,
            birth:birth,
            address:model.address,
            email:model.email,
            idCard:model.idCard,
            phone:model.phone,
            classId:model.classId,
            className:model.className,
            departmentId:model.departmentId,
            departmentName:model.departmentName,
            createTime:model.createTime,
            updateTime:model.updateTime,
          }).then(res=>{
              console.log(res);
          })
            /* this.$refs[form].validate(valid => {
                if (valid) {
                    this.$message.success('注册成功');
                    setTimeout(() => {
                        this.$router.push('/login');
                    }, 1000);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            }); */
        },
        toLogin() {
            this.$router.push('/login');
        },
        selectPlace(value){
          this.form.address = value[0] + value[1] + value[2]
          console.log(this.form.address);
        },
        classChange(value){
          this.classList.map(item=>{
            if(value == item.classId){
              this.form.className = item.className
            }
          })
        },
        departmentChange(value){
          this.departmentList.map(item=>{
            if(value == item.departmentId){
              this.form.departmentName = item.departmentName
            }
          })
        },
        isBlank(value){
        	if (value == '' || value == undefined){
        		return '';
        	}
        	return value;
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 220px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>

//      getList() {
        	
//        	let formdata = new FormData()
//			for(let key in this.param) {
//				formdata.append(key, this.param[key])
//			}	

//      	axios.post('/user/get_user_list.do',formdata).then(res=>{
////      		console.log(res.data.status);
////      		console.log(res.data.data.list);
//	        	if(res.data.status == 0){
//					this.tableData = res.data.data.list;
//					this.pageTotal = res.pageTotal || 10;
//	        	} else if (res.data.status == 1) {
//	        		this.$message.error(res.data.msg);
//	        	} else if (res.data.status == 10) {
//	        		this.$message.error(res.data.msg);
//	        	} else {
//	        		this.$message.error(res.data.msg);
////	        		this.$message.error('不合法请求！');
//	        	} 	
//		    }).catch(err=>{
//	            console.log('请求失败！！');
//	            return false;
//	    	})

//      },